"""
自定义权限
"""
import re
from django.contrib.auth.backends import ModelBackend, UserModel
from django.contrib.auth.models import AnonymousUser
from rest_framework.permissions import BasePermission
# from django.db.models import F
# from apis.system.models import ApiWhiteList


class CustomPermission(BasePermission):
    """自定义权限"""

    def has_permission(self, request, view):
        if isinstance(request.user, AnonymousUser):
            return False
        # 判断是否是超级管理员
        if request.user.is_superuser:
            request.query_params._mutable = True
            request.query_params['_api_name'] = ''
            return True
        else:
            api = request.path  # 当前请求接口
            method = request.method  # 当前请求方法
            method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH']
            method = method_list.index(method)
            # ***接口白名单***
            # api_white_list = ApiWhiteList.objects.values(permission__api=F('url'), permission__method=F('method'))
            # api_white_list = [
            #     str(item.get('permission__api').replace('{id}', '([a-zA-Z0-9-]+)')) + ":" + str(
            #         item.get('permission__method')) + '$' for item in api_white_list if item.get('permission__api')]
            # ******** #
            if not hasattr(request.user, 'role'):
                return False
            # 获取当前用户的角色拥有的所有接口
            user_api_list = request.user.role.values('permission__api', 'permission__method', 'permission__name')
            api_dict = dict()
            for item in user_api_list:
                if item.get('permission__api'):
                    item_api = str(item.get('permission__api').replace('{id}', '([0-9]+)'))
                    item_method = str(item.get('permission__method'))
                    key = '{}:{}$'.format(item_api, item_method)
                    api_dict[key] = str(item.get('permission__name'))

            new_api = api + ':' + str(method)
            for item, api_name in api_dict.items():
                match_obj = re.match(item, new_api, re.M | re.I)
                if match_obj is None:
                    continue
                else:
                    request.query_params._mutable = True
                    request.query_params['_api_name'] = api_name
                    return True
            else:
                return False

            # api_list = [
            #     str(item.get('permission__api').replace('{id}', '([a-zA-Z0-9-]+)')) + ':' + str(
            #         item.get('permission__method')) + '$' for item in user_api_list if item.get('permission__api')]
            # new_api_ist = api_white_list + api_list
            # new_api_ist = api_list
            # new_api = api + ':' + str(method)
            # for item in new_api_ist:
            #     match_obj = re.match(item, new_api, re.M | re.I)
            #     if match_obj is None:
            #         continue
            #     else:
            #         return True
            # else:
            #     return False


class CustomModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            # UserModel().set_password(password)
            return
        else:
            if user.check_password(password):
                return user
            return
